package com.example.aslongastoday.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.aslongastoday.db.helper.MemoryDatabaseHelper;
import com.example.aslongastoday.domain.Memory;
import com.example.aslongastoday.domain.MemoryComparator;
import com.example.aslongastoday.util.TimeUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MemoryDao {
    private SQLiteDatabase db;

    public MemoryDao(Context context) {
        MemoryDatabaseHelper dbHelper = new MemoryDatabaseHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    /**
     * 从数据库的表中获取当前的所有的回忆录的数据
     * @return
     */
    public List<Memory> getAllMemories() {
        List<Memory> memories = new ArrayList<>();
        // 直接做全查询
        Cursor cursor = db.query(MemoryDatabaseHelper.TABLE_NAME, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_ID));

            // 因为我们保存在数据库中的时间是以yyyy-MM-dd的格式的字符串，但是我们在Java中是用Date来保存日期数据，所以在数据库这里需要转换下
            String timeString = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_TIME));
            HashMap<String,Integer> map = TimeUtil.getTimeParts(timeString);
            // 这里的新建方法是增量新建，最终获取到的时间的值是输入的值加上1900，而默认的月份的值0是一月依次类推！所以用这样的方式构建Date类需要注意转化！
            Date time = new Date(map.get("year"),map.get("month"),map.get("day"));

            String name = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_NAME));
            boolean isAnniversary = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_IS_ANNIVERSARY)) == 1;
            int iconIndex = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_ICON_INDEX));
            String message = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_MESSAGE));
            Memory memory = new Memory(id, time, name, isAnniversary, iconIndex, message);

            memories.add(memory);
        }
        cursor.close();
        // 在回传前按时间进行排序
        Collections.sort(memories, new MemoryComparator());
        return memories;
    }

    /**
     * 新增一条回忆数据到数据库中
     * @param memory
     */
    public void addMemory(Memory memory) {
        ContentValues values = new ContentValues();
        values.put(MemoryDatabaseHelper.COLUMN_TIME, TimeUtil.toFormatTime(memory.getTime()));
        values.put(MemoryDatabaseHelper.COLUMN_NAME, memory.getName());
        values.put(MemoryDatabaseHelper.COLUMN_IS_ANNIVERSARY, memory.isAnniversary() ? 1 : 0);
        values.put(MemoryDatabaseHelper.COLUMN_ICON_INDEX, memory.getIconID());
        values.put(MemoryDatabaseHelper.COLUMN_MESSAGE, memory.getMessage());
        db.insert(MemoryDatabaseHelper.TABLE_NAME, null, values);
    }

    /**
     * 将一条修改过的回忆数据更新到数据库中
     * @param memory
     */
    public void updateMemory(Memory memory) {
        ContentValues values = new ContentValues();
        values.put(MemoryDatabaseHelper.COLUMN_TIME, TimeUtil.toFormatTime(memory.getTime()));
        values.put(MemoryDatabaseHelper.COLUMN_NAME, memory.getName());
        values.put(MemoryDatabaseHelper.COLUMN_IS_ANNIVERSARY, memory.isAnniversary() ? 1 : 0);
        values.put(MemoryDatabaseHelper.COLUMN_ICON_INDEX, memory.getIconID());
        values.put(MemoryDatabaseHelper.COLUMN_MESSAGE, memory.getMessage());
        String whereClause = MemoryDatabaseHelper.COLUMN_ID + "=?";
        String[] whereArgs = {String.valueOf(memory.getId())};
        db.update(MemoryDatabaseHelper.TABLE_NAME, values, whereClause, whereArgs);
    }

    /**
     * 从数据库中删除对应的回忆项
     * @param memory
     */
    public void deleteMemory(Memory memory) {
        String whereClause = MemoryDatabaseHelper.COLUMN_ID + "=?";
        String[] whereArgs = {String.valueOf(memory.getId())};
        db.delete(MemoryDatabaseHelper.TABLE_NAME, whereClause, whereArgs);
    }

    /**
     * 基于给定的文本与回忆名进行模糊匹配从而实现模糊查询
     * @param name
     * @return
     */
    public List<Memory> getMemoriesByName(String name) {
        List<Memory> memories = new ArrayList<>();
        String selection = MemoryDatabaseHelper.COLUMN_NAME + " LIKE ?";
        String[] selectionArgs = {"%" + name + "%"};

        Cursor cursor = db.query(MemoryDatabaseHelper.TABLE_NAME, null, selection, selectionArgs, null, null, null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_ID));

            //因为我们保存在数据库中的时间是以yyyy-MM-dd的格式的字符串，但是我们在Java中是用Date来保存日期数据，所以在数据库这里需要转换下
            String timeString = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_TIME));
            HashMap<String,Integer> map = TimeUtil.getTimeParts(timeString);
            // 这里的新建方法是增量新建，最终获取到的时间的值是输入的值加上1900，而默认的月份的值0是一月依次类推！所以用这样的方式构建Date类需要注意转化！
            Date time = new Date(map.get("year"),map.get("month"),map.get("day"));

            String memoryName = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_NAME));
            boolean isAnniversary = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_IS_ANNIVERSARY)) == 1;
            int iconIndex = cursor.getInt(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_ICON_INDEX));
            String message = cursor.getString(cursor.getColumnIndexOrThrow(MemoryDatabaseHelper.COLUMN_MESSAGE));
            Memory memory = new Memory(id, time, memoryName, isAnniversary, iconIndex, message);
            memories.add(memory);
        }
        cursor.close();
        Collections.sort(memories, new MemoryComparator());
        return memories;
    }
}
